/**
 * 此文件为自定义上传图片组件，后续可自行优化;详情参数请参考vant官网
 */
import { API } from '../../utils/network/api';
import { showContent } from '../../utils/network/network';
const app = getApp();

var domain = wx.getStorageSync("domain");


Component({
  /**
   * 组件的属性列表
   */
  properties: {
    //最大图片张数
    maxCount: {
      type: Number,
      value: 3
    },
    //是否开启图片多选，部分安卓机型不支持
    multiple: {
      type: Boolean,
      value: true
    },
    //图片对象格式
    imageFormat: {
      type: Object,
      //默认返回格式为{fileId:'',filePath:''}
      value: {
        id: 'fileId',
        url: 'filePath'
      }
    },
    //图片剪裁模式
    imageFit: {
      type: String,
      value: 'aspectFit'
    },
    //上传显示文字
    uploadText: {
      type: String,
      value: '上传图片'
    },
    // 压缩图片（图片质量）
    quality: {
      type: Number,
      value: 80
    },
    fileLists: {
      type: Array,
      value: []
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    fileList: [], //图片文件列表
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //选择图片
    async afterRead(event) {
      let fileList = event.detail.file; //图片数组列表
      const compressImageList = await this.compressImageList(fileList, this.properties.quality); //压缩图片
      this.setData({
        fileList: this.data.fileList.concat(compressImageList.map(i => ({
          type: "image",
          url: i.tempFilePath
        })))
      })
      this.updataCount();
    },
    //更新选择图片张数
    updataCount() {
      this.triggerEvent('updataImageCount', {
        key: `${this.properties.imageFormat.url}Count`,
        value: this.data.fileList.length
      })
    },
    deleteImage(event) {
      let fileList = this.data.fileList;
      fileList.splice(event.detail.index, 1);
      this.setData({
        fileList
      }, () => {
        this.updataCount();
      })
    },
    //获取组件图片数组
    getImageList() {
      return this.data.fileList;
    },
    /**
     * 处理后端需要的数据格式
     */
    dealImageDataFormat() {
      if (this.data.fileList) {
        const id = this.properties.imageFormat.id;
        const url = this.properties.imageFormat.url;
        let list = {
          [`${id}`]: [],
          [`${url}`]: []
        };
        this.data.fileList.forEach(item => {
          list[`${id}`].push(item[id]);
          list[`${url}`].push(item[`${url}`]);
        })
        return list;
      }
    },
    //压缩图片
    compressImageList(list, quality = 10) {
      return new Promise((resolve, reject) => {
        let compressUrl = [];
        list.forEach((item, index) => {
          wx.compressImage({
            src: item.url,
            quality,
            success: res => {
              compressUrl.push(res);
              index == list.length - 1 ? resolve(compressUrl) : '';
            },
            fail: err => {
              showContent(err);
            }
          })
        })

      })
    },
    //上传图片
    uploadImage() {
      return new Promise((resolve, reject) => {
        let fileList = this.data.fileList;
        if (fileList.length == 0) resolve([]);
        let _this = this;
        wx.getSystemInfo({
          success: res => {
            let version, limitVersion;
            limitVersion = 8; //版本控制
            version = parseFloat(res.system.match(/[0-9.]/g).join(''));
            //Android <= 7
            version <= limitVersion ? '' :
              //上传图片
              fileList.forEach((item, index) => {
                if (item.status != 'done') {
                  //image loading
                  item.status = 'uploading';
                  item.message = '上传中';
                  wx.uploadFile({
                    filePath: item.url,
                    name: 'file',
                    url: `${domain}${app.globalData.env === "develop" ? API.upload : API.tencentUpload}`, //拼接图片上传路径
                    header: {
                      platformType: "MINIAPP",
                      Authorization: wx.getStorageSync("token")
                    },
                    timeout: 30 * 1000,
                    success(res) {
                      const result = JSON.parse(res.data);
                      if (result.code === 0) {
                        let imageFormat = _this.properties.imageFormat;
                        let iamgeItem = {};
                        const { fileId, filePath } = result.data;
                        iamgeItem[imageFormat.id] = fileId;
                        iamgeItem[imageFormat.url] = filePath; //提交表单url
                        iamgeItem.url = filePath; //vant 图片url
                        iamgeItem.status = 'done';
                        iamgeItem.message = '上传成功';
                        _this.setData({
                          [`fileList[${index}]`]: iamgeItem, //组件预览数据格式
                        })
                        if (index >= fileList.length - 1) {
                          // _this.triggerEvent('upLoadImage', _this.dealImageDataFormat());
                          resolve(_this.data.fileList);
                        }
                      } else {
                        showContent(res)
                        reject(res);
                      }
                    },
                    fail(err) {
                      showContent(err);
                      reject(err);
                    }
                  })
                } else if (index >= fileList.length - 1) {
                  // _this.triggerEvent('upLoadImage', _this.dealImageDataFormat());
                  resolve(_this.data.fileList);
                }
              })
          },
          fail: err => {
            showContent(err);
          }
        })
      })
    },
    //检查图片列表
    checkoutImageList() {
      return this.data.fileList.length;
    }
  },
  observers: {
    fileLists: function (val) {
      if (val) {
        let list = this.data.fileList;
        if (this.properties.maxCount > 1) {
          list.push(...list);
        } else {
          list = val;
        }
        this.setData({
          fileList: list
        })
      }
    }
  }
})